'use strict';
module.exports = {
	/**
	 * 改变收藏状态
	 * @url client/course/pub/change_star 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid, course_id, status } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		if (uid == null) return {
			code: -1,
			msg: "用户未登录"
		}
		const transaction = await vk.baseDao.startTransaction();

		try {
			// 收藏
			if (status == 0) {
				await vk.baseDao.add({
					dbName: "user-star",
					dataJson: {
						user_id: uid,
						course_id: course_id
					}
				});
				await transaction.commit();
				return {
					code: 0,
					msg: "收藏成功",
					noStatus: 1
				}
			}
			// 取消收藏
			if (status == 1) {
				await vk.baseDao.del({
					dbName: "user-star",
					whereJson: {
						user_id: uid,
						course_id: course_id
					}
				});
				await transaction.commit();
				return {
					code: 0,
					msg: "已取消收藏",
					noStatus: 0
				}
			}

		} catch (err) {
			// 事务回滚
			await transaction.rollback();
			console.error(`transaction error`, err)
			return {
				code: -1,
				msg: "收藏失败",
				err: {
					message: err.message,
					stack: err.stack
				}
			}
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
